using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 数据管理器，统一管理所有游戏数据
/// </summary>
public class DataManager : MonoBehaviour
{
    [Header("数据引用")]
    public PlayerData playerData;
    public GameState gameState;

    [Header("配置数据")]
    public CardConfig cardConfig;
    // 可以添加其他配置引用：EnemyConfig, RelicConfig等

    private static DataManager _instance;
    public static DataManager Instance => _instance;

    // 快速访问属性
    public static PlayerData Player => Instance?.playerData;
    public static GameState GameState => Instance?.gameState;

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(gameObject);
            return;
        }
        
        _instance = this;
        DontDestroyOnLoad(gameObject);
        
        InitializeData();
        
        Debug.Log("[DataManager] 数据管理器初始化完成");
    }

    /// <summary>
    /// 初始化游戏数据
    /// </summary>
    private void InitializeData()
    {
        // 确保必要的组件存在
        if (playerData == null)
        {
            playerData = FindObjectOfType<PlayerData>();
            if (playerData == null)
            {
                GameObject playerObj = new GameObject("PlayerData");
                playerData = playerObj.AddComponent<PlayerData>();
            }
        }

        if (gameState == null)
        {
            gameState = FindObjectOfType<GameState>();
            if (gameState == null)
            {
                GameObject stateObj = new GameObject("GameState");
                gameState = stateObj.AddComponent<GameState>();
            }
        }

        // 初始化配置数据
        if (cardConfig == null)
        {
            cardConfig = Resources.Load<CardConfig>("CardConfig");
        }
    }

    /// <summary>
    /// 开始新游戏
    /// </summary>
    public void StartNewGame()
    {
        // === 步骤 1: 强制查找并确保引用存在 (防止在场景切换时丢失) ===
        if (gameState == null)
        {
            gameState = FindObjectOfType<GameState>();
        }

        if (playerData == null)
        {
            playerData = FindObjectOfType<PlayerData>();
        }
        
        // 如果查找失败，则报错并退出
        if (gameState == null || playerData == null)
        {
            Debug.LogError("DataManager: 无法找到关键单例 (GameState/PlayerData)，新游戏无法启动！");
            return; 
        }
        gameState.ResetGameState();
        
        // 重置玩家数据
        playerData.ResetForCombat();
        // 在这里加上您需要的 HP 重置
        playerData.currentHP = playerData.maxHP;
        playerData.gold = 0;
        playerData.credit = 0;
        playerData.relics.Clear();
        playerData.potions.Clear();
        
        // 初始化初始牌组
        InitializeStarterDeck();
        
        Debug.Log("新游戏开始");
    }

    /// <summary>
    /// 初始化初始牌组
    /// </summary>
    private void InitializeStarterDeck()
    {
        gameState.masterDeck.Clear();
        
        // 这里应该通过CardFactory创建初始牌组
        // 暂时添加一些基础卡牌ID
        string[] starterCards = {
            "strike", "strike", "strike", "strike", "strike",
            "defend", "defend", "defend", "defend",
            "bash"
        };
        
        // 注意：这里需要CardFactory来实际创建卡牌实例
        Debug.Log($"初始化初始牌组，共 {starterCards.Length} 张卡牌");
    }

    /// <summary>
    /// 保存游戏
    /// </summary>
    public void SaveGame()
    {
        // TODO: 实现保存游戏逻辑
        Debug.Log("保存游戏");
    }

    /// <summary>
    /// 加载游戏
    /// </summary>
    public void LoadGame()
    {
        // TODO: 实现加载游戏逻辑
        Debug.Log("加载游戏");
    }

    /// <summary>
    /// 获取当前战斗中的敌人列表
    /// </summary>
    public List<EnemyData> GetCurrentEnemies()
    {
        return gameState.currentEnemies;
    }

    /// <summary>
    /// 添加遗物到玩家
    /// </summary>
    public void AddRelicToPlayer(string relicId)
    {
        playerData.AddRelic(relicId);
    }

    /// <summary>
    /// 检查玩家是否拥有指定遗物
    /// </summary>
    public bool PlayerHasRelic(string relicId)
    {
        return playerData.HasRelic(relicId);
    }

    /// <summary>
    /// 获取游戏统计信息
    /// </summary>
    public string GetGameStatistics()
    {
        return gameState.GetGameStats();
    }

    /// <summary>
    /// 清理数据（游戏结束时）
    /// </summary>
    public void Cleanup()
    {
        gameState.currentEnemies.Clear();
        playerData.ResetForCombat();
    }
}